import json
from datetime import datetime

from django.http import HttpRequest, JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView

from chatCompletion.service.ChatService import ChatService
from chatCompletion.entity.result.BaseResult import HttpResult


# Create your views here.

class ChatCompletionView(APIView):
    @csrf_exempt
    def post(self, request: HttpRequest, *args, **kwargs):
        data = json.loads(request.body)
        response_msg = ChatService.simple_chat(data['message'])
        return HttpResult.success(data=response_msg)

    def get(self, request: HttpRequest, *args, **kwargs):
        return HttpResult.success()


class WebSocketResponse:
    @staticmethod
    def generate_response(status="success", code=200, message="Operation completed", data=None):
        """
        生成标准化的 WebSocket 响应
        :param status: 响应状态 ("success" 或 "error")
        :param code: 状态码 (200、400、500等)
        :param message: 响应消息描述
        :param data: 响应数据内容，默认为空字典
        :return: JSON 格式的响应字符串
        """
        response = {
            "status": status,
            "code": code,
            "message": message,
            "data": data if data is not None else {},
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }
        return json.dumps(response)

    @staticmethod
    def success(message="Operation completed", data=None):
        """
        生成成功响应
        :param message: 成功消息描述
        :param data: 成功数据内容
        :return: JSON 格式的成功响应字符串
        """
        return WebSocketResponse.generate_response(status="success", code=200, message=message, data=data)

    @staticmethod
    def error(message="An error occurred", code=400, data=None):
        """
        生成错误响应
        :param message: 错误消息描述
        :param code: 错误状态码
        :param data: 错误数据内容
        :return: JSON 格式的错误响应字符串
        """
        return WebSocketResponse.generate_response(status="error", code=code, message=message, data=data)

